# -*- coding: utf-8 -*-
from flask import (
    Flask,
    render_template,
    redirect,
    send_from_directory,
    request,
    make_response,
    current_app,
    jsonify
)

try:
    from urllib.parse import urljoin
except ImportError:
    from urlparse import urljoin

from . import template_folder, static_folder


def create_app(config):
    app = Flask(
        __name__,
        template_folder=template_folder,
        static_folder=static_folder
    )
    app.config['SECRET_KEY'] = config.get('secret', 'secret!')

    app.debug = config.get('debug', False)
    # set app.debug with True to show DebugToolbar
    # from flask_debugtoolbar import DebugToolbarExtension
    # toolbar = DebugToolbarExtension(app)
    app = with_decorator(app)

    return app

def with_decorator(app):

    @app.template_global()
    def cdn_static_url(filename):
        # TODO: add cdn config
        # refer: https://stackoverflow.com/questions/35824412/serve-static-files-from-a-cdn-rather-than-flask-in-production
        static_url = app.config.get('STATIC_URL')

        if static_url:
            return urljoin(static_url, filename)

        return url_for('static', filename=filename)

    @app.endpoint('static')
    def cdn_endpoint_static(filename):
        # TODO: add cdn config
        static_url = app.config.get('STATIC_URL')

        if static_url:
            return redirect(urljoin(static_url, filename))

        # return send_from_directory(app.static_folder, filename)
        return app.send_static_file(filename)

    return app